// pages/kanJia/kanJiaList.js
import {
  getKanJiaGoods,
  sendKanJia,
  getKanJia,
  getHelpList,
  helpKanJia
} from '../../api/kanJia'

import {
  addCart
} from '../../api/cart'

var app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    statusBarHeight: '',
    titleBarHeight: '',
    goodsList: [],
    page: 1,
    finish: false,
    page1: 1,
    finish1: false,
    launch: false,
    kanJiaData: null,
    isMyKanJia: false,
    infoList: [],
    textList: ['感情深，刀法深', '再接再厉，很快就成功了', '看来老夫宝刀已老', '我还是回家再练练刀法吧', '不好意思，下次多用点力'],
    timer: null,
    timeCount: 0
  },

  async buy() {
    let cartData = {
      skuId: this.data.kanJiaData.skuId,
      num: 1,
      cartType: 'KANJIA'
    }
    let res = await addCart(cartData, wx.getStorageSync('access_token'))
    if (res && res.code == 10000) {
      wx.redirectTo({
        url: "/pages/pay-order/pay-order?orderType=KANJIA"
      })
    } else {
      wx.showToast({
        title: res.msg,
        icon: 'none'
      })
    }
  },

  async helpHis() {
    if( app.globalData.userInfo.kanjia > 0 ){
      wx.showToast({
        title: '仅限新用户参与！',
        icon: 'none'
      })
      return
    }
    let res = await helpKanJia(this.data.kanJiaData.id, wx.getStorageSync('access_token'))
    console.log(res)
    if (res && res.code == 10000) {
      wx.showToast({
        title: '助力成功！',
      })
      let kanJia = await getKanJia(this.data.kanJiaData.id, wx.getStorageSync('access_token'))
      this.setData({
        kanJiaData: kanJia.data
      })
      this.setData({
        infoList: [],
        page1: 1,
        finish: false
      })
      this.getKanJiaUser()
    } else {
      wx.showToast({
        title: res.msg,
        icon: 'none'
      })
    }
  },

  back() {
    wx.reLaunch({
      url: '../index/index' //返回上一级页面
    })
  },

  async kan(e) {
    if (e.currentTarget.dataset.stock == 0) {
      wx.showToast({
        title: '该商品已被抢光',
        icon: 'none'
      })
    }
    let id = e.currentTarget.dataset.id
    let res = await sendKanJia(id, wx.getStorageSync('access_token'))
    if (res && res.code == 10000) {
      wx.showToast({
        title: '参与成功！',
      })
      let kanJia = await getKanJia('', wx.getStorageSync('access_token'))
      this.setData({
        kanJiaData: kanJia.data,
        isMyKanJia: kanJia.data.memberId == app.globalData.userInfo.id,
      })
      this.setData({
        infoList: [],
        page1: 1,
        finish1: false
      })
      console.log(this.data.kanJiaData)
      this.getKanJiaUser()
    } else {
      wx.showToast({
        title: res.msg,
        icon: 'none'
      })
    }
  },

  async getKanJiaUser() {
    if (this.data.finish1) {
      return
    }
    let res = await getHelpList(this.data.kanJiaData.id, this.data.page1, wx.getStorageSync('access_token'))
    console.log(res)
    if (res && res.code == 10000) {
      if (res.data.records.length > 0) {
        this.setData({
          infoList: [...this.data.infoList, ...res.data.records],
          page1: this.data.page1 + 1
        })
      } else {
        this.setData({
          finish1: true
        })
      }
    }
  },

  async getData() {
    if (this.data.finish) {
      return
    }
    let res = await getKanJiaGoods(this.data.page, '', wx.getStorageSync('access_token'))
    console.log(res)
    if (res && res.code == 10000) {
      if (res.data.records.length > 0) {
        this.setData({
          goodsList: [...this.data.goodsList, ...res.data.records],
          page: this.data.page + 1
        })
      } else {
        this.setData({
          finish: true
        })
      }
    }
  },

  setBarHeight() {
    if (app.globalData && app.globalData.statusBarHeight && app.globalData.titleBarHeight) {
      this.setData({
        statusBarHeight: app.globalData.statusBarHeight,
        titleBarHeight: app.globalData.titleBarHeight
      });
    } else {
      let that = this
      wx.getSystemInfo({
        success: function (res) {
          if (!app.globalData) {
            app.globalData = {}
          }
          if (res.model.indexOf('iPhone') !== -1) {
            app.globalData.titleBarHeight = 44
          } else {
            app.globalData.titleBarHeight = 48
          }
          app.globalData.statusBarHeight = res.statusBarHeight
          that.setData({
            statusBarHeight: app.globalData.statusBarHeight,
            titleBarHeight: app.globalData.titleBarHeight
          })
        },
        failure() {
          that.setData({
            statusBarHeight: 0,
            titleBarHeight: 0
          });
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    this.setBarHeight()
    wx.showLoading({
      title: '加载中...',
      mask: true
    })
    // 判断当前是否读取到globalData
    if (app.globalData.userInfo) {
      // 清除定时器 解除加载状态
      clearInterval(this.data.timer)
      this.setData({
        myInfo: app.globalData.userInfo,
      })
    } else {
      // 读取失败，定时器重新执行
      this.data.timer = setInterval(() => {
        console.log(this.data.timeCount)
        if( this.data.timeCount == 3 ){
          clearInterval(this.data.timer)
        }
        this.onLoad({
          id: options.id
        })
        this.data.timeCount = this.data.timeCount + 1
      }, 1000)
      return
    }
    if (!wx.getStorageSync('access_token')) {
      wx.showModal({
        title: '请先登录',
        content: '',
        showCancel: false,
        success: (res) => {
          wx.reLaunch({
            url: '../my/my?kan=1' //返回上一级页面
          })
        }
      })
      return
    }
    let rep
    // 判断是不是邀请进来的用户
    if (options.id) {
      rep = await getKanJia(options.id, wx.getStorageSync('access_token'))
      if( rep.data.promotionStatus == 'END' || rep.data.status == 'END' || rep.data.status == 'SUCCESS' || rep.data.status == 'FAIL' ){
        wx.showToast({
          title: '该砍价已结束',
          icon: 'none'
        })
      }
    } else {
      rep = await getKanJia('', wx.getStorageSync('access_token'))
      this.getData()
    }
    console.log(rep)
    if (rep.data.promotionStatus == 'END' || rep.data.status == 'END' || rep.data.status == 'FAIL') {
      rep.data = {
        help: false,
        launch: false,
        pass: false
      }
    }
    this.setData({
      kanJiaData: rep.data,
      isMyKanJia: rep.data.memberId == app.globalData.userInfo.id,
    })
    console.log(this.data.kanJiaData, this.data.isMyKanJia)
    wx.hideLoading({
      success: (res) => {},
    })
    this.getKanJiaUser()
    wx.hideShareMenu()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    console.log(res)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: '免费拿好礼，你敢砍我敢送！',
      path: `/pages/kanJia/kanJiaList?id=${ this.data.kanJiaData.id }`,
      imageUrl: 'https://mallcdn.oss-cn-beijing.aliyuncs.com/15995521152779264.jpg'
    }
  }
})